package org.uoss.webapp.framework.struts2.tags;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.components.Component;
import org.apache.struts2.views.jsp.ComponentTagSupport;
import org.uoss.core.util.ValidationUtil;
import org.uoss.webapp.framework.struts2.tags.components.Struts2PagerComponent;

import com.opensymphony.xwork2.util.ValueStack;

public final class Struts2PagerTag extends ComponentTagSupport
{
	private static final long serialVersionUID = 1096053115303634263L;
	private String totalCount;
	private String pageIndex;
	private String pageSize;
	private String pageURL;
	
	@Override
	public Component getBean(ValueStack arg0, HttpServletRequest arg1, HttpServletResponse arg2)
	{
		return new Struts2PagerComponent(arg0);
	}

	@Override
	protected void populateParams()
	{
		super.populateParams();
		Struts2PagerComponent pager = (Struts2PagerComponent)this.component;
		pager.setTotalCount(String.valueOf(this.getTagId(this.getTotalCount())));
		pager.setPageIndex(String.valueOf(this.getTagId(this.getPageIndex())));
		pager.setPageSize(String.valueOf(this.getTagId(this.getPageSize())));
		pager.setPageURL(String.valueOf(this.getTagId(this.getPageURL())));
	}

	public String getTotalCount()
	{
		return totalCount;
	}

	public void setTotalCount(String totalCount)
	{
		this.totalCount = totalCount;
	}

	public String getPageIndex()
	{
		return pageIndex;
	}

	public void setPageIndex(String pageIndex)
	{
		this.pageIndex = pageIndex;
	}

	public String getPageSize()
	{
		return pageSize;
	}

	public void setPageSize(String pageSize)
	{
		this.pageSize = pageSize;
	}

	public String getPageURL()
	{
		return pageURL;
	}

	public void setPageURL(String pageURL)
	{
		this.pageURL = pageURL;
	}
	
	private boolean isTagId(String refValue)
	{
		if (ValidationUtil.isEmpty(refValue))
			return false;
		if (refValue.startsWith("%{") && refValue.endsWith("}"))
			return true;
		return false;
	}
	
	private Object getTagId(String refValue)
	{
		if(!this.isTagId(refValue))
		{
			return refValue;
		}
		String refId = refValue.toString().substring(2, refValue.toString().length() - 1);
		return this.getStack().findValue(refId);
	}
}
